﻿using DependencyInjectionHelperLib.Attributes;
using DependencyInjectionHelperLib.Eunms;
using Microsoft.Extensions.DependencyInjection;
using static DependencyInjectionHelperLib.Helpers.DIRegistrationHelper;

namespace DependencyInjectionHelperLib.Extensions
{
    /// <summary>
    /// IServiceCollection 扩展方法
    /// </summary>
    public static class IServiceCollectionExtension
    {
        /// <summary>
        /// 自动将特性 DIRegistrationAttribute 注册到 IServiceCollection 容器中
        /// </summary>
        /// <param name="serviceCollection">注册到 IServiceCollection 容器中</param>
        public static void AutoRegisterServices(this IServiceCollection serviceCollection)
        { // 对遍历到的对象进行 OnAttributeFound 操作。
            RegisterServices<DIRegistrationAttribute>(serviceCollection, OnAttributeFound);
        }

        /// <summary>
        /// 根据特性遍历到的对象执行的操作。
        /// </summary>
        /// <param name="attribute">特性</param>
        /// <param name="serviceCollection">容器</param>
        /// <param name="serviceType">注册的服务类型</param>
        /// <param name="registerMethods">注册的服务的方法集合</param>
        private static void OnAttributeFound(
            DIRegistrationAttribute attribute,
            IServiceCollection serviceCollection,
            Type serviceType,
            Dictionary<Lifetimes, Action<IServiceCollection, Type, Type>> registerMethods
        )
        {
            if (registerMethods.TryGetValue(attribute.Lifetime, out var registerMethod))
            {
                // 使用映射中的方法注册服务 这里注册的是： serviceType 和 implementationType
                registerMethod(serviceCollection, serviceType, serviceType);
            }

            foreach (var iType in attribute.InterfaceTypes)
            {
                if (registerMethods.TryGetValue(attribute.Lifetime, out var registerInterfaceMethod))
                {
                    // 使用映射中的方法注册服务 这里注册的是： interface 和 implementationType
                    registerInterfaceMethod(serviceCollection, iType, serviceType);
                }
            }
        }
    }
}